-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday_09.ex
97 lines (90 loc) · 2.17 KB
/
day_09.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
defmodule AdventOfCode.Day09 do
import AdventOfCode.Util
def part1(args) do
args
|> parseInput()
|> headPositions()
# 1
|> nextKnotPositions()
|> MapSet.new()
|> MapSet.size()
end
def part2(args) do
args
|> parseInput()
|> headPositions()
# 1
|> nextKnotPositions()
# 2
|> nextKnotPositions()
# 3
|> nextKnotPositions()
# 4
|> nextKnotPositions()
# 5
|> nextKnotPositions()
# 6
|> nextKnotPositions()
# 7
|> nextKnotPositions()
# 8
|> nextKnotPositions()
# 9
|> nextKnotPositions()
|> MapSet.new()
|> MapSet.size()
end
def headPositions(instructions) do
instructions
|> String.codepoints()
|> Enum.scan([0, 0], fn x, acc -> AdventOfCode.Day09.updateHead(acc, x) end)
end
def nextKnotPositions(previousKnotPositions) do
previousKnotPositions
|> Enum.scan([0, 0], fn head, acc -> AdventOfCode.Day09.updateKnot(head, acc) end)
end
def parseInput(input) do
input
|> String.trim()
|> String.split("\n")
|> Enum.map(
&(String.split(&1, " ")
|> then(fn [dir, num] -> String.duplicate(dir, String.to_integer(num)) end))
)
|> Enum.join()
end
def updateHead(h, "R"), do: getE(h)
def updateHead(h, "L"), do: getW(h)
def updateHead(h, "U"), do: getN(h)
def updateHead(h, "D"), do: getS(h)
def updateKnot(h, t) do
cond do
h == t -> t
h == getN(t) -> t
h == getNN(t) -> getN(t)
h == getS(t) -> t
h == getSS(t) -> getS(t)
h == getW(t) -> t
h == getWW(t) -> getW(t)
h == getE(t) -> t
h == getEE(t) -> getE(t)
h == getSE(t) -> t
h == getSSE(t) -> getSE(t)
h == getSEE(t) -> getSE(t)
h == getSESE(t) -> getSE(t)
h == getNE(t) -> t
h == getNNE(t) -> getNE(t)
h == getNEE(t) -> getNE(t)
h == getNENE(t) -> getNE(t)
h == getSW(t) -> t
h == getSSW(t) -> getSW(t)
h == getSWW(t) -> getSW(t)
h == getSWSW(t) -> getSW(t)
h == getNW(t) -> t
h == getNNW(t) -> getNW(t)
h == getNWW(t) -> getNW(t)
h == getNWNW(t) -> getNW(t)
true -> raise "unknown skip"
end
end
end